package cn.com.xy.sms.sdk.util;

import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import cn.com.xy.sms.sdk.Iservice.XyCallBack;
import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.db.entity.RecordActionManager;
import cn.com.xy.sms.sdk.db.entity.PopupActionInfo;
import cn.com.xy.sms.sdk.db.entity.PopupActionManager;
import cn.com.xy.sms.sdk.db.entity.SysParamEntityManager;
import cn.com.xy.sms.sdk.iccid.IccidLocationUtil;
import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.net.NetUtil;
import cn.com.xy.sms.sdk.net.util.ServerResposeParseUtil;

public class SceneCountActionUtil {

    public static void postSceneCountAction() {
        boolean ispost = false;
        // 周期
        final String curTime = DateUtils.getCurrentTimeString("yyyyMMdd");// 当前日期
        String lastPostTime = getLastSceneCountActionTime(Constant.getContext());
        if (lastPostTime == null) {// 第一次上报
            ispost = true;
        } else {
            ispost = DateUtils.compareDateString(// 间隔大于一天，把今天之前的上传
                    curTime, DateUtils.addDays(lastPostTime, "yyyyMMdd", 1),// 增加一天
                    "yyyyMMdd");
        }
        if (ispost) {
            try {
                String reportData = getReportDataString(curTime);
                if (!StringUtils.isNull(reportData)) {
                    XyCallBack callBack = new XyCallBack() {

                        @Override
                        public void execute(Object... obj) {
                            if (obj != null) {
                                String resultCode = obj[0].toString();
                                if (resultCode.equals("0") && obj.length == 2) {
                                    String response = obj[1].toString();
                                    // 解析返回的报文
                                    boolean resultBack = ServerResposeParseUtil
                                            .parseSceneCountActionResponseResultCode(response);
                                    if (resultBack) {
                                        // 记录上报的日期
                                        SysParamEntityManager.setParam(
                                                "LastSceneCountActionUpdate",
                                                curTime);
                                        // 删除数据
                                        PopupActionManager
                                                .deleteInfoByDate(curTime);
                                        RecordActionManager
                                                .deleteInfoByDate(curTime);
                                    }
                                }
                            }
                        }

                    };

                    // //内网地址
                    // NetUtil.executeLoginBeforeHttpRequest(reportData,
                    // "990005", callBack,
                    // "http://192.168.1.119:8080/statservice/stat",true);
                    //外网地址
                    if(NetUtil.isEnhance()){
                    	 NetUtil.executeLoginBeforeHttpRequest(reportData, "990005", callBack,
                                 NetUtil.STATSERVICE_URL,true);
                    }
                   
                }
            } catch (Throwable e) {
//                e.printStackTrace();
                LogManager.e(Constant.TAG, "postSceneCountAction: ", e);
            }
        }
    }

    public static String getReportDataString(String updateDate) {
        StringBuffer sb = new StringBuffer();
        // 多天的数据
        List<PopupActionInfo> dateList = PopupActionManager
                .queryDates(updateDate);
        sb.append("<SceneStat>");
        if (dateList != null && dateList.size() > 0) {
            for (PopupActionInfo dateInfo : dateList) {
                /*
                 * t1;date1;iccidmd5;情景id,识别次数，展现次数，动作类型=次数#动作类型=次数&情景id,识别次数，展现次数
                 * ,动作类型=次数#动作类型=次数
                 */
                sb.append("t1;");
                String aDate = dateInfo.date;
                sb.append(aDate + ";");
                String iccid = StringUtils.getMD5(IccidLocationUtil
                        .getICCID(Constant.getContext()));
                sb.append(iccid + ";");

                // 一天的数据
                List<PopupActionInfo> popupActionInfoList = PopupActionManager
                        .queryByDate(aDate);
                for (int i = 0; i < popupActionInfoList.size(); i++) {
                    PopupActionInfo info = popupActionInfoList.get(i);
                    if (i != 0) {
                        sb.append("&amp;");
                    }
                    String sceneId = info.sceneId;
                    sb.append(sceneId + ",");
                    sb.append(info.parseTimes + ",");
                    sb.append(info.popupTimes + ",");
                    // 操作按钮点击
                    JSONArray buttonActionArr = RecordActionManager
                            .queryByIdDate(sceneId, aDate);
                    if(buttonActionArr == null){
                        continue;
                    }
                    try{
                        for (int j = 0; j < buttonActionArr.length(); j++) {
                            JSONObject bInfo = buttonActionArr.getJSONObject(j);
                            if (j != 0) {
                                sb.append("#");
                            }
                            /* SDK-376 mobaohua 20160331 start */
                            String actionType = bInfo.getString(RecordActionManager.ACTION_CODE);
                            if (StringUtils.isNull(actionType)) {
                                actionType = bInfo.getString(RecordActionManager.ACTION_TYPE);
                            }
                            sb.append(actionType + "=");
//                            sb.append(bInfo.getString(RecordActionManager.ACTION_TYPE) + "=");
                            /* SDK-376 mobaohua 20160331 end */
                            sb.append(bInfo.getString(RecordActionManager.TIMES));
                        }
                    }catch(Throwable e){
//                        e.printStackTrace();
                        LogManager.e(Constant.TAG, "getReportDataString: ", e);

                    }
                }
                sb.append("\n");
            }
            sb.append("</SceneStat>");

            return sb.toString();
        } else {
            return null;
        }

    }

    public static String getLastSceneCountActionTime(Context context) {

        return SysParamEntityManager.getStringParam(context,
                "LastSceneCountActionUpdate");
    }

    public static void setLastSceneCountActionTime(Context context,
            String curDate) {

        SysParamEntityManager.setParam("LastSceneCountActionUpdate", curDate);
    }

}
